package com.wasion.pwportable.jsi;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.webkit.WebView;

import com.google.gson.Gson;
import com.wasion.core.db.Pagination;
import com.wasion.core.db.storage.SqliteStorage;
import com.wasion.core.db.storage.SqliteStorageListener.DataInsertListener;
import com.wasion.core.db.storage.SqliteStorageListener.DataQueryListener;
import com.wasion.core.db.storage.SqliteStorageListener.DataUpdateListener;
import com.wasion.core.db.storage.StorageQuery;
import com.wasion.core.db.storage.StorageQuery.SortOrder;
import com.wasion.core.util.DateTimeUtil;
import com.wasion.core.util.StringUtil;
import com.wasion.pwportable.activity.PwPortableActivity;
import com.wasion.pwportable.dao.sd.SchemeSDDBDao;
import com.wasion.pwportable.dao.sd.TerminalSDDBDao;
import com.wasion.pwportable.dao.sd.WorkLineSDDBDao;
import com.wasion.pwportable.domain.po.Scheme;
import com.wasion.pwportable.domain.po.WorkLine;

/**
 * 
 * @ClassName: WorkLineJSI
 * @Description: 线路JavaScriptInterface，对线路操作交互接口<br/>
 *               1. 增加/修改线路 <br/>
 *               2. 删除线路 <br/>
 *               3. 获取线路 <br/>
 * @author 高意
 * @date 2014-8-1 下午2:57:06
 * 
 */
public class WorkLineJSI {

	// 应用上下文
	private Context context;

	// webview，浏览器窗口
	private WebView webView;

	// Sqlite存储实例
	private SqliteStorage sqliteStorage = null;

	// Google的Json转换工具
	private Gson gson = new Gson();

	// 是否点击查询按钮触发事件
	private boolean isQuery;

	// 线路数据库访问接口
	private WorkLineSDDBDao workLineSDDBDao = null;

	WorkLine workLine = new WorkLine();

	public WorkLineJSI(Context context) {
		this.context = context;
		this.webView = PwPortableActivity.getWebView();
		this.sqliteStorage = SqliteStorage.getInstance(this.context);
		workLineSDDBDao = new WorkLineSDDBDao(context);
	}

	/**
	 * 
	 * @Title: addOrModifyWorkLine
	 * @Description: 新增/修改线路
	 * @param
	 * @return
	 * @throws
	 */
	public void addOrModifyWorkLine(final String jsonStr) {

		workLine = gson.fromJson(jsonStr, WorkLine.class);
		workLine.setTime(DateTimeUtil.getCurrentDate());

		StorageQuery storageQuery = new StorageQuery();
		storageQuery.equals("linename", workLine.getLinename());
		if (0 == workLine.get_id()) { // 为0，新增
			sqliteStorage.findData(storageQuery, workLineSDDBDao,
					new DataQueryListener() {

						public void onFailure(int errorCode, String errorMessage) {
							JSIHelper.showToast(context, "添加失败!");
						}

						public void onSuccess(List<?> paramList) {

							if (null != paramList && 0 < paramList.size()) {
								JSIHelper
										.showToast(context, "线路名称已存在, 不能重复添加!");
								return;
							}

							sqliteStorage.insertData(workLine, workLineSDDBDao,
									new DataInsertListener() {

										public void onSuccess(long paramLong) {

											if (0 == paramLong) {
												JSIHelper.showToast(context,
														"添加失败!");
												return;
											}

											JSIHelper.showToast(context,
													"添加成功!");
											Map<String, Object> map = new HashMap<String, Object>();
											map.put("type", "workline");

											String result = gson.toJson(map);
											webView.loadUrl("javascript:editSuccessCallback("
													+ result + ")");
										}

										public void onFailure(int errorCode,
												String errorMessage) {
											JSIHelper.showToast(context,
													"添加失败!");
										}
									});
						}
					});
		} else { // 修改
			storageQuery.notEqual("_id", workLine.get_id());
			sqliteStorage.findData(storageQuery, workLineSDDBDao,
					new DataQueryListener() {

						public void onFailure(int errorCode, String errorMessage) {
							JSIHelper.showToast(context, "修改失败!");
						}

						public void onSuccess(List<?> paramList) {

							if (null != paramList && 0 < paramList.size()) {
								JSIHelper
										.showToast(context, "线路名称已存在, 不能重复添加!");
								return;
							}

							sqliteStorage.updateData(workLine, workLineSDDBDao,
									new DataUpdateListener() {

										public void onSuccess(long paramLong) {

											if (0 == paramLong) {
												JSIHelper.showToast(context,
														"修改失败!");
												return;
											}

											JSIHelper.showToast(context,
													"修改成功!");
											Map<String, Object> map = new HashMap<String, Object>();
											map.put("type", "workline");

											String result = gson.toJson(map);
											webView.loadUrl("javascript:editSuccessCallback("
													+ result + ")");
										}

										public void onFailure(int errorCode,
												String errorMessage) {
											JSIHelper.showToast(context,
													"修改失败!");
										}
									});
						}
					});
		}
	}

	/**
	 * 
	 * @Title: removeWorkLine
	 * @Description: 删除线路
	 * @param
	 * @return
	 * @throws
	 */
	public void removeWorkLine(final String _id) {

		if (StringUtil.isEmpty(_id)) {
			JSIHelper.showToast(context, "线路唯一标识不能为空!");
			return;
		}

		StorageQuery storageQuery = new StorageQuery();
		storageQuery.equals("lineid", _id);

		sqliteStorage.findData(storageQuery, new TerminalSDDBDao(context),
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "删除线路失败!");
					}

					public void onSuccess(List<?> paramList) {

						if (null != paramList && 0 < paramList.size()) {
							JSIHelper.showToast(context, "线路下存在终端, 不能删除!");
							webView.loadUrl("javascript:removePauseCallback()");
							return;
						}

						StorageQuery sq = new StorageQuery();
						sq.equals("_id", Integer.parseInt(_id));

						sqliteStorage.deleteData(sq, workLineSDDBDao,
								new DataUpdateListener() {

									public void onSuccess(long paramLong) {
										JSIHelper.showToast(context, "删除成功!");
										webView.loadUrl("javascript:removeSuccuessCallback()");
									}

									public void onFailure(int errorCode,
											String errorMessage) {
										JSIHelper.showToast(context, "删除失败!");
									}
								});
					}
				});

	}

	/**
	 * 
	 * @Title: queryWorkLines
	 * @Description: 获取线路
	 * @param
	 * @return
	 * @throws
	 */
	public void queryWorkLines(final String jsonStr) {

		workLine = gson.fromJson(jsonStr, WorkLine.class);

		StorageQuery storageQuery = new StorageQuery();

		if (null != workLine) {
			int _id = workLine.get_id();
			if (0 != _id) {
				storageQuery.equals("_id", _id);
			}
		}

		sqliteStorage.findData(storageQuery, workLineSDDBDao,
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "查询线路失败!");
					}

					public void onSuccess(List<?> paramList) {

						if (null != paramList && 0 < paramList.size()) {
							try {
								Map<String, Object> map = new HashMap<String, Object>();
								if (null != workLine) {
									map.put("flag", "modify");
								} else {
									map.put("flag", "query");
								}
								map.put("list", paramList);
								String result = gson.toJson(map);

								webView.loadUrl("javascript:loadWorkLines("
										+ result + ")");
							} catch (Exception e) {
								JSIHelper.showToast(context, e.getMessage());
							}
						}
					}
				});
	}

	/**
	 * 
	 * @Title: queryWorkLinesByPage
	 * @Description: 分页获取线路
	 * @param
	 * @return
	 * @throws
	 */
	public void queryWorkLinesByPage(final String jsonStr) {

		StorageQuery storageQuery = new StorageQuery();
		try {
			JSONObject jsObj = new JSONObject(jsonStr);
			isQuery = jsObj.getBoolean("isQuery");

			if (!jsObj.isNull("pId")) {
				storageQuery.equals("schemeid", jsObj.getString("pId"));
			}
			if (!jsObj.isNull("linename")) {
				storageQuery.like("linename", jsObj.getString("linename"));
			}

			int size = Pagination.DEFAULT_PAGE_SIZE;
			if (!jsObj.isNull("pagesize")) {
				storageQuery.setLimit(Integer.parseInt(jsObj
						.getString("pagesize")));
			} else {
				storageQuery.setLimit(Pagination.DEFAULT_PAGE_SIZE);
			}

			if (!jsObj.isNull("page")) {
				storageQuery.setOffset(size
						* (Integer.parseInt(jsObj.getString("page")) - 1));
			} else {
				storageQuery.setOffset(size * (Pagination.DEFAULT_PAGE - 1));
			}

			storageQuery.addSort("time", SortOrder.DESC);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		sqliteStorage.findData(storageQuery, workLineSDDBDao,
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "查询线路失败!");
					}

					@SuppressWarnings("unchecked")
					public void onSuccess(List<?> paramList) {

						if (isQuery
								&& (null == paramList || 0 == paramList.size())) {
							String jsonStr = gson.toJson(paramList);

							webView.loadUrl("javascript:queryWorkLinesByPageCallback("
									+ jsonStr + ")");
							return;
						}

						if (null != paramList && 0 < paramList.size()) {

							for (WorkLine wl : (List<WorkLine>) paramList) {
								String schemeId = wl.getSchemeid();

								SchemeSDDBDao schemeSDDBDao = new SchemeSDDBDao(
										context);
								schemeSDDBDao.startReadableDatabase(false);
								List<Scheme> schemes = schemeSDDBDao.queryList(
										new String[] { "schemename" }, "_id=?",
										new String[] { schemeId }, null, null,
										null, null);
								schemeSDDBDao.closeDatabase(false);

								if (0 < schemes.size()) {
									wl.setSchemename(schemes.get(0)
											.getSchemename());
								}
							}

							try {
								String jsonStr = gson.toJson(paramList);

								webView.loadUrl("javascript:queryWorkLinesByPageCallback("
										+ jsonStr + ")");
							} catch (Exception e) {
								JSIHelper.showToast(context, e.getMessage());
							}
						} else {
							JSIHelper.showToast(context, "已加载所有线路!");
						}
					}
				});
	}

}
